import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface MenuMeta {
    selectIndex: string;
    check: boolean;
}

interface MenuItem {
    index: string;
    title: string;
    path?: string;
    parentId?: string;
    type?: string;
    icon?: string;
    name?: string;
    component?: string;
    menuType?: number;
    meta?: MenuMeta;
    children?: MenuItem[];
}

interface MenuState {
    menus: MenuItem[];
    activeMenu: string;
}

// 从localStorage获取初始菜单
const getInitialMenus = (): MenuItem[] => {
    try {
        const menuData = localStorage.getItem('menuData');
        return menuData ? JSON.parse(menuData) : [];
    } catch (error) {
        console.error('Failed to parse menu data from storage', error);
        return [];
    }
};

const initialState: MenuState = {
    menus: getInitialMenus(),
    activeMenu: '',
};

const menuSlice = createSlice({
    name: 'menu',
    initialState,
    reducers: {
        setMenus: (state, action: PayloadAction<MenuItem[]>) => {
            state.menus = action.payload;
            localStorage.setItem('menuData', JSON.stringify(action.payload));
        },
        setActiveMenu: (state, action: PayloadAction<string>) => {
            state.activeMenu = action.payload;
        },
    },
});

export const { setMenus, setActiveMenu } = menuSlice.actions;
export default menuSlice.reducer;